package com.wqr.mobile.android.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import com.wqr.mobile.android.ui.R;
import com.wqr.mobile.android.ui.api.API;

public class GridFragment extends Fragment implements OnScrollListener, API {
	private static final String TAG = GridFragment.class.getSimpleName();
	private ArrayAdapter<String> mAdapter;
	private View mLoadItem;
	private Handler mHandler;

	public GridFragment(Handler handler) {
		this.mHandler = handler;
	}

	private List<String> createData(int n) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < n; i++) {
			list.add("item-" + i + 1);
		}
		return list;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy");
		super.onDestroy();
	}

	@Override
	public void onPause() {
		Log.i(TAG, "onPause");
		super.onPause();
	}

	@Override
	public void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.i(TAG, "onCreateView");
		View root = inflater.inflate(R.layout.layout_grid, null);
		GridView gridView = (GridView) root.findViewById(R.id.gridView1);
		mLoadItem = root.findViewById(R.id.gridLoadItem);
		mHandler.post(new DataMaker());
		mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
		gridView.setAdapter(mAdapter);
		gridView.setOnScrollListener(this);
		mHandler.sendEmptyMessage(FINISHED);
		return root;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem + visibleItemCount == totalItemCount) {
			mLoadItem.setVisibility(view.VISIBLE);
			list.addAll(createData(5));
			mAdapter.notifyDataSetChanged();
			mLoadItem.setVisibility(view.GONE);
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	List<String> list = new ArrayList<String>();

	class DataMaker implements Runnable {
		@Override
		public void run() {
			for (int i = 0; i < 10; i++) {
				list.add("item-" + i + 1);
			}
		}

		List<String> getList() {
			return list;
		}
	}
}
